package com.mcx.modules.socket;

import com.mcx.modules.Role;
import com.mcx.modules.RoleMgr;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @program: programme
 * @description: SocketServer
 * @author: qiu bo yang
 * @create: 2020-10-09 09:56
 **/
@Slf4j
@Data
@Component
@NoArgsConstructor
public class SocketServer implements Runnable {
    private int port=1314;
    private boolean started;
    private ServerSocket serverSocket;
    // 防止重复创建socket线程链接对象浪费资源
    private ExecutorService executorService = Executors.newCachedThreadPool();

    public void start(){
        try {
            serverSocket = new ServerSocket(port);
            started = true;
            log.info("Socket服务已启动，占用端口： {}", serverSocket.getLocalPort());

            Thread mThread = new Thread(this::ListenClientCallBack);
            mThread.start();

            // 后面改成线程
        } catch (IOException e) {
            log.error("端口冲突,异常信息：{}", e);
            System.exit(0);
        }
    }

    @Override
    public void run() {
        ListenClientCallBack();
    }

    private void ListenClientCallBack(){
        // 线程主体
        while  (true){
            try {
                // 开启socket监听，接收客户端请求
                Socket socket = serverSocket.accept();
                log.info("监听到客户端："+socket.toString());
                // 判断是否是特殊服务器
                if (socket.getInetAddress().getHostAddress().equals("192.168.1.1")) {

                } else {
                    //一个角色 就相当于一个客户端
                    Role role = new Role();
                    ClientSocket clientSocket = new ClientSocket(socket, role);

                    //把角色添加到角色管理
                    RoleMgr.getInstance().getAllRole().add(role);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
